package  
{
	import fl.motion.Keyframe;
	import flash.display.MovieClip;
	import flash.events.KeyboardEvent;
	import flash.ui.Keyboard;
	import Util.Directions;
	import Util.Physics;
	/**
	 * ...
	 * @author Thiago Árvore
	 */
	public class Player extends MovieClip
	{
		private var speedX:Number;
		private var speedY:Number;
		private var bulletManager:BulletManager;
		private var main:Main
		
		private var right:Boolean = false;
		private var left:Boolean = false;
		private var up:Boolean = false;
		private var shooting:Boolean = false;
		
		public function Player(speed:Number, main:Main) 
		{
			this.main = main
			this.speedX = speed
			this.speedY = Physics.GRAVITY;
			this.bulletManager = new BulletManager(main);
			
			main.stage.addEventListener(KeyboardEvent.KEY_DOWN, pressKey);
			main.stage.addEventListener(KeyboardEvent.KEY_UP, releaseKey);
		}
		
		public function getSpeed():Number
		{
			return this.speedX;
		}
		
		public function setSpeed(v:Number):void
		{
			this.speedX = v;
		}
		
		private function pressKey(e:KeyboardEvent):void
		{
			if (e.keyCode == Keyboard.RIGHT)
			{
				right = true;
				if (this.scaleX < 0)
				{
					this.scaleX *= -1;
				}
			}
			else if (e.keyCode == Keyboard.LEFT)
			{
				left = true;
				if (this.scaleX > 0)
				{
					this.scaleX *= -1;
				}
			}
			
			if (e.keyCode == Keyboard.UP)
			{
				trace("test");
				if (!up)
				{
					up = true;
				}
				
			}
			
			if (e.keyCode == Keyboard.SPACE)
			{
				shooting = true;
			}
		}
		
		private function releaseKey(e:KeyboardEvent):void
		{
			if (e.keyCode == Keyboard.RIGHT)
			{
				right = false;
			}
			else if (e.keyCode == Keyboard.LEFT)
			{
				left = false;
			}
			
			if (e.keyCode == Keyboard.UP)
			{
				up = false;
			}
			
			if (e.keyCode == Keyboard.SPACE)
			{
				shooting = false;
			}
		}
		
		public function movePlayer():void
		{
			if (right)
			{
				this.x += speedX;
			}
			else if (left)
			{
				this.x -= speedX;
			}
				
			if (shooting)
			{
				var bulletDirection:int = 0;
				if (this.scaleX < 0)
				{
					bulletDirection = Directions.LEFT;
				}
				else if (this.scaleX > 0)
				{
					bulletDirection = Directions.RIGHT;
				}
				bulletManager.createBullet(this, 10, bulletDirection);
			}
		}
			
			
		public function checkPosition():void
		{
			if (this.y + this.height >= main.stage.stageHeight)
			{
				this.y = main.stage.stageHeight - this.height;
				if (up)
				{
					speedY = -40
					up = false;
				}
			}
			if (this.x <= this.width)
			{
				this.x = this.width;
			}
			if (this.x + this.width >= main.stage.stageWidth)
			{
				this.x = main.stage.stageWidth - this.width;
			}
		}
		
		public function update():void
		{
			this.movePlayer();
			bulletManager.update();
			this.y += speedY
			speedY += Physics.GRAVITY;
			checkPosition();
		}
	}

}